<!-- author: xuett -->
<!-- date: 2023-02-07 09:26:42 -->
<!-- description: tree排序 -->
<template>
  <G-drawer v-model:drawerShow="drawerShow" title="排序" :show-header="true" :width="450">
    <template #content>
      <div class="tree-box">
        <div class="title">
          <div class="title-text">名称</div>
          <div class="title-but">
            <div>上移</div>
            <div>下移</div>
            <div>置顶</div>
            <div>置底</div>
          </div>
        </div>
        <el-tree
          ref="tree"
          :expand-on-click-node="false"
          :data="treeData"
          :node-key="nodeKey"
          :allow-drop="treeAllowDrop"
          default-expand-all
          :props="treeProps"
          draggable
          @node-drop="nodeDrop"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <div class="sort-operation">
                <el-button icon="Top" title="上移" @click.stop="sortOperation(node, data, 1)"></el-button>
                <el-button icon="Bottom" title="下移" @click.stop="sortOperation(node, data, 2)"></el-button>
                <el-button icon="Upload" type="primary" plain title="置顶" @click.stop="sortOperation(node, data, 3)"></el-button>
                <el-button icon="Download" type="primary" plain title="置底" @click.stop="sortOperation(node, data, 4)"></el-button>
              </div>
            </span>
          </template>
        </el-tree>
      </div>
    </template>
    <template #footer>
      <div>
        <el-button type="primary" :disabled="!treeData.length" @click="onSubmit">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </G-drawer>
</template>

<script setup>
const $props = defineProps({
  sortShow: {
    type: Boolean,
    default: false
  },
  sortTree: {
    type: Array,
    default: () => []
  },
  nodeKey: {
    type: String,
    default: ""
  },
  treeProps: {
    type: Object,
    default: () => {}
  },
  level: {
    type: String,
    default: ""
  },
  deptName: {
    type: String,
    default: ""
  }
});
const $emit = defineEmits(["update:sortShow", "callBackData"]);
const drawerShow = computed({
  get: () => $props.sortShow,
  set: (val) => $emit("update:sortShow", val)
});

watch(
  () => $props.sortTree,
  (newVal) => {
    state.treeData = newVal ? JSON.parse(JSON.stringify(newVal)) : [];
  }
);
onMounted(() => {
  state.treeData = $props.sortTree ? JSON.parse(JSON.stringify($props.sortTree)) : [];
});

const state = reactive({
  treeData: []
});

const { treeData } = toRefs(state);

const tree = ref(null);
// 上下移
const sortOperation = (node, data, type) => {
  let key = $props.nodeKey;
  let arr = node.level == 1 ? node.parent.data : node.parent.data.children;
  let index = arr.findIndex((item) => item[key] == data[key]);
  if (type == 1 && index > 0) {
    //上移
    let prevKey = arr[index - 1][key];
    tree.value.remove(node);
    tree.value.insertBefore(data, prevKey);
  } else if (type == 2 && index < arr.length - 1) {
    //下移
    let nextKey = arr[index + 1][key];
    tree.value.remove(node);
    tree.value.insertAfter(data, nextKey);
  } else if (type == 3 && index > 0) {
    //置顶
    let firstKey = arr[0][key];
    tree.value.remove(node);
    tree.value.insertBefore(data, firstKey);
  } else if (type == 4 && index < arr.length - 1) {
    //置底
    let lastKey = arr[arr.length - 1][key];
    tree.value.remove(node);
    tree.value.insertAfter(data, lastKey);
  }

  let obj = {
    id: data.id,
    name: data.name,
    parentData: arr,
    parentId: data.parentId == "0" ? "" : data.parentId || ""
  };
  mapnodeDropList(obj);
};

//限制-列表类数据项-不能添加为父子级
const treeAllowDrop = (data, end, type) => {
  if ($props.level == "1") {
    return type !== "inner";
  } else if (end.data.deptName == $props.deptName) {
    return type !== "prev" && type !== "next";
  } else {
    return true;
  }
};
//拖拽成功事件
const nodeDrop = (node, end, seat) => {
  // console.log("seat", seat,end.data,end.parent);
  // console.log("seat", seat);
  if (seat == "inner") {
    // 层级-排序,end为父级节点
    node.data.parentId = end.data.id;
  } else {
    // 同级-排序，end为前后节点
    node.data.parentId = end.parent.data.id;
  }
  let obj = {
    id: node.data.id,
    name: node.data.name,
    parentData: seat == "inner" ? end.data.children : end.parent.data.children || end.parent.data,
    parentId: node.data.parentId || ""
  };
  // console.log("name", obj.name);
  // console.log("parentData", obj.parentData);
  mapnodeDropList(obj);
};

const nodeDropList = ref([]);
//保存排序-数据
const mapnodeDropList = (val) => {
  // console.log("parentData", val.parentData);
  // console.log("newLList-------1", nodeDropList.value);
  let item = nodeDropList.value;
  // let item = JSON.parse(JSON.stringify(nodeDropList.value));
  // let newLList = nodeDropList.value.filter((item) => item.id != val.id);
  let newLList = item.filter((item) => item.id != val.id);
  newLList.push(val);
  // console.log("newLList-------2", newLList);
  nodeDropList.value = [];
  nodeDropList.value = newLList;
};

//保存-回传父级数据
const onSubmit = () => {
  let sortData = nodeDropList.value;
  // console.log(123, sortData);
  sortData.forEach((item) => {
    // if (item.parentId == "") {
    //   item.orderNum = sortData[sortData.length - 1].parentData.findIndex((a) => a.id == item.id);
    // } else {
    //   item.orderNum = item.parentData.findIndex((a) => a.id == item.id);
    // }

    if (item.parentData && item.parentData.length) {
      item.orderNum = item.parentData.findIndex((a) => a.id == item.id);
    }
    // delete item.parentData;
  });
  $emit("callBackData", sortData);
  handleClose();
  nodeDropList.value = [];
};

//取消
const handleClose = () => {
  state.treeData = $props.sortTree ? JSON.parse(JSON.stringify($props.sortTree)) : [];
  drawerShow.value = false;
};
</script>

<style scoped lang="scss">
.tree-box {
  width: 100%;
  overflow: auto;
  :deep(.el-tree-node__label) {
    flex: 1;
  }
  .title {
    display: flex;
    font-size: 14px;
    height: 40px;
    line-height: 40px;
    background-color: #f5f7fa;
    border: 1px solid #eaeaea;
    margin-bottom: 10px;
    .title-text {
      flex: 1;
      text-align: center;
    }
    .title-but {
      display: flex;
      div {
        height: 24px;
        padding: 0px 5px;
      }
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding: 5px 8px 5px 0;
    .sort-operation {
      .el-button {
        height: 24px;
        padding: 0px 4px;
      }
    }
  }
}
.el-overlay {
  :deep(.el-drawer__body) {
    border: 1px $G-colorD solid;
  }
}
::-webkit-scrollbar {
  width: 0px;
}
</style>
